﻿Public Class xtf_ListadoBase 
    Public WithEvents dtt_DataTable As New DataTable
    Public PERMISONuevo As String = ""
    Public PERMISOModificar As String = ""
    Public PERMISOEliminar As String = ""
    Public PERMISOImprimir As String = ""

    Public Sub FiltrarColumnas()
        Dim int_IDUsuario As Integer = UsuarioLOG.idusuario
        Dim obj_config_usuariocolumna_ As New cls_config_usuariocolumna_
        gdv_general.BeginUpdate()
        If obj_config_usuariocolumna_.Buscarxidusuarioxmodulo(int_IDUsuario, Me.Name) Then
            'For Each columna As DevExpress.XtraGrid.Columns.GridColumn In gdv_general.Columns
            '    columna.Visible = True
            'Next
            'For Each columna As String In obj_config_usuariocolumna_.columnas.Split(New Char() {";"}, StringSplitOptions.RemoveEmptyEntries)
            '    gdv_general.Columns(CInt(columna)).Visible = False
            'Next
            'Dim index As Integer = 0
            'For Each columna As String In obj_config_usuariocolumna_.columnasOrden.Split(New Char() {";"}, StringSplitOptions.RemoveEmptyEntries)
            '    gdv_general.Columns(CInt(columna)).VisibleIndex = index
            '    index += 1
            'Next
            SetLayoutData(gdv_general, obj_config_usuariocolumna_.xml)
            If gdv_general.VisibleColumns(0).FilterInfo.FilterString <> "" Then
                Dim filter As String = gdv_general.VisibleColumns(0).FilterInfo.FilterString
                filter = Replace(filter, "[" & gdv_general.VisibleColumns(0).ToString & "] Like '", "")
                filter = Strings.Left(filter, filter.Length - 1)
                txt_filtrarcol1.Text = Replace(filter, "%", "")
                txt_filtrarcol1.SelectAll()
            End If
        End If

        PerzonalizarControl(gdc_general)
        'gdv_general.BestFitColumns()
        gdv_general.EndUpdate()
    End Sub

    Private Function GetLayoutData(ByRef prm_GridView As DevExpress.XtraGrid.Views.Grid.GridView) As Byte()
        Dim stream As New System.IO.MemoryStream()
        prm_GridView.SaveLayoutToStream(stream)
        Return stream.GetBuffer()
    End Function

    Private Sub SetLayoutData(ByRef prm_GridView As DevExpress.XtraGrid.Views.Grid.GridView, ByVal data As Byte())
        If data Is Nothing OrElse data.Length = 0 Then
            Return
        End If
        Dim stream As New System.IO.MemoryStream(data)
        Try
            prm_GridView.RestoreLayoutFromStream(stream)
            Dim config_parametro As New cls_config_parametro_
            gdv_general.OptionsView.ColumnAutoWidth = config_parametro.Buscar("grillaAutoWidth").valor
        Catch ex As Exception
            Throw New Exception("Wrong data format", ex)
        End Try
    End Sub

    Public Sub FiltrarColumnas(ByRef prm_GridControl As DevExpress.XtraGrid.GridControl, ByRef prm_GridView As DevExpress.XtraGrid.Views.Grid.GridView)
        Dim int_IDUsuario As Integer = UsuarioLOG.idusuario
        Dim obj_config_usuariocolumna_ As New cls_config_usuariocolumna_
        prm_GridView.BeginUpdate()
        If obj_config_usuariocolumna_.Buscarxidusuarioxmodulo(int_IDUsuario, Me.Name) Then
            For Each columna As DevExpress.XtraGrid.Columns.GridColumn In prm_GridView.Columns
                columna.Visible = True
            Next
            For Each columna As String In obj_config_usuariocolumna_.columnas.Split(New Char() {";"}, StringSplitOptions.RemoveEmptyEntries)
                prm_GridView.Columns(CInt(columna)).Visible = False
            Next
            Dim index As Integer = 0
            For Each columna As String In obj_config_usuariocolumna_.columnasOrden.Split(New Char() {";"}, StringSplitOptions.RemoveEmptyEntries)
                prm_GridView.Columns(CInt(columna)).VisibleIndex = index
                index += 1
            Next
        End If

        PerzonalizarControl(prm_GridControl)
        prm_GridView.BestFitColumns()
        prm_GridView.EndUpdate()
    End Sub

#Region "Total registros ..."

    Private Sub gdv_general_RowCountChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gdv_general.RowCountChanged
        bsi_registros.Caption = "Registros: " & gdv_general.RowCount
        If gdv_general.RowCount = 0 Then
            bbi_imprimirMenu.Enabled = False
        Else
            bbi_imprimirMenu.Enabled = True
        End If
    End Sub

#End Region

    Private Sub bbi_cerrar_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_cerrar.ItemClick
        Me.Close()
    End Sub

    Private Sub gridView1_DoubleClick(ByVal sender As Object, ByVal e As EventArgs) Handles gdv_general.DoubleClick
        Dim view As DevExpress.XtraGrid.Views.Grid.GridView = CType(sender, DevExpress.XtraGrid.Views.Grid.GridView)
        Dim pt As Point = view.GridControl.PointToClient(Control.MousePosition)
        DoRowDoubleClick(view, pt)
    End Sub

    Public Overridable Sub DoRowDoubleClick(ByVal view As DevExpress.XtraGrid.Views.Grid.GridView, ByVal pt As Point)
        Dim info As DevExpress.XtraGrid.Views.Grid.ViewInfo.GridHitInfo = view.CalcHitInfo(pt)
        If info.InRow OrElse info.InRowCell Then
            Dim colCaption As String
            If info.Column Is Nothing Then
                colCaption = "N/A"
            Else
                colCaption = info.Column.GetCaption()
            End If
            bbi_Modificar.PerformClick()
        End If
    End Sub

    Public Overridable Sub gdv_general_FocusedRowChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs) Handles gdv_general.FocusedRowChanged
        
    End Sub

    Private Sub bbi_columnas_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_columnas.ItemClick
        'Dim obj_ABMconfig_usuariocolumna As New xtf_ABMconfig_usuariocolumna(gdv_general, Me.Name)
        'If obj_ABMconfig_usuariocolumna.ShowDialog() = Windows.Forms.DialogResult.OK Then
        '    FiltrarColumnas()
        'End If
        gdv_general.ColumnsCustomization()
    End Sub

    Public Overridable Sub bbi_Nuevo_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_Nuevo.ItemClick
        If ComprobarPermiso(PERMISONuevo) Then
            Cargarregistroestado_()
            CargarLista()
            bsi_estado.Caption = "Cargando..."
            Application.DoEvents()
            Dim ABM As Object
            ABM = CType(Activator.CreateInstance(Type.GetType(Replace(Application.ProductName, " ", "_") & "." & Strings.Left(Replace(Me.Name, "xtf_LISTADO", "xtf_ABM"), Replace(Me.Name, "xtf_LISTADO", "xtf_ABM").Length - 1), True, True)), Form)
            ABM.Nuevo(Me)
            ABM.ControlarModificaciones(ABM.lac_general.items)
            bsi_estado.Caption = "Listo"
        End If
        Strings.Left(Replace(Me.Name, "xtf_LISTADO", "xtf_ABM"), Replace(Me.Name, "xtf_LISTADO", "xtf_ABM").Length - 2)
    End Sub

    Public Overridable Sub bbi_Modificar_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_modificar.ItemClick
        If ComprobarPermiso(PERMISOModificar) Then
            Try
                Dim barrio As Object 'New cls_barrio_
                barrio = Activator.CreateInstance(Type.GetType(Replace(Application.ProductName, " ", "_") & "." & Replace(Me.Name, "xtf_LISTADO", "cls_"), True, True))
                If gdv_general.SelectedRowsCount > 0 Then
                    If barrio.Buscar(gdv_general.GetDataRow(gdv_general.GetSelectedRows(0))("Identificador (ID)")) Then
                        bsi_estado.Caption = "Cargando..."
                        Application.DoEvents()
                        Dim ABM As Object 'New xtf_ABMbarrio
                        ABM = CType(Activator.CreateInstance(Type.GetType(Replace(Application.ProductName, " ", "_") & "." & Strings.Left(Replace(Me.Name, "xtf_LISTADO", "xtf_ABM"), Replace(Me.Name, "xtf_LISTADO", "xtf_ABM").Length - 1), True, True)), Form)
                        ABM.Modificar(barrio, Me, gdv_general.GetDataRow(gdv_general.GetSelectedRows(0)))
                        ABM.ControlarModificaciones(ABM.lac_general.items)
                        bsi_estado.Caption = "Listo"
                    End If
                End If

            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End If
    End Sub

    Public Overridable Sub bbi_Eliminar_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_eliminar.ItemClick
        If ComprobarPermiso(PERMISOEliminar) Then
            Try
                If gdv_general.SelectedRowsCount > 0 Then
                    If ErrManagerShow("000005", Me) = DialogResult.Yes Then
                        Dim eliminarRegistro As Boolean = False
                        If UsuarioLOG.esroot Then
                            If ErrManagerShow("001023", Me) = DialogResult.Yes Then
                                eliminarRegistro = True
                            End If
                        End If


                        Dim objeto As Object
                        objeto = Activator.CreateInstance(Type.GetType(Replace(Application.ProductName, " ", "_") & "." & Replace(Me.Name, "xtf_LISTADO", "cls_"), True, True))

                        If eliminarRegistro Then
                            objeto.Eliminar(gdv_general.GetDataRow(gdv_general.GetSelectedRows(0))("Identificador (ID)"))
                        Else
                            objeto.buscar(gdv_general.GetDataRow(gdv_general.GetSelectedRows(0))("Identificador (ID)"))
                            objeto.registro.idregistroestado = 2
                            objeto.modificar()
                        End If

                        dtt_DataTable.Rows.Remove(gdv_general.GetDataRow(gdv_general.GetSelectedRows(0)))
                    End If
                End If
            Catch ex As Exception
                'Dim frmError As New frm_ErrorManager(ex.Message)
            End Try
        End If

    End Sub

    Private Sub xtf_ListadoBase_Activated(sender As Object, e As System.EventArgs) Handles Me.Activated
        'bbi_actualizar_ItemClick(Nothing, Nothing)
        txt_filtrarcol1.SelectAll()
        txt_filtrarcol1.Focus()
    End Sub

    Private Sub xtf_ListadoBase_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        guardar_config_usuariocolumna_()
    End Sub

    Private Sub guardar_config_usuariocolumna_()
        'Dim str_Columnas As String = ""
        'Dim str_ColumnasOrden As String = ""
        'For i As Integer = 0 To gdv_general.Columns.Count - 1
        '    If gdv_general.Columns(i).Visible = False Then
        '        str_Columnas &= i & ";"
        '    End If
        'Next
        'For i As Integer = 0 To gdv_general.VisibleColumns.Count - 1
        '    str_ColumnasOrden &= gdv_general.VisibleColumns(i).AbsoluteIndex & ";"
        'Next

        Dim obj_config_usuariocolumna_ As New cls_config_usuariocolumna_
        If obj_config_usuariocolumna_.Buscarxidusuarioxmodulo(UsuarioLOG.idusuario, Me.Name) Then
            'Dim flagMod As Boolean = False
            'If obj_config_usuariocolumna_.xml.Length <> GetLayoutData(gdv_general).Length Then
            '    flagMod = True
            'End If
            'If obj_config_usuariocolumna_.columnas <> str_Columnas Then
            '    flagMod = True
            '    obj_config_usuariocolumna_.columnas = str_Columnas
            'End If
            'If obj_config_usuariocolumna_.columnasOrden <> str_ColumnasOrden Then
            '    flagMod = True
            '    obj_config_usuariocolumna_.columnasOrden = str_ColumnasOrden
            'End If
            'If flagMod Then
            ' If ErrManagerShow("001016") = DialogResult.Yes Then
            obj_config_usuariocolumna_.xml = GetLayoutData(gdv_general)
            obj_config_usuariocolumna_.Modificar()
            'End If
            'End If
        Else
            obj_config_usuariocolumna_.xml = GetLayoutData(gdv_general)
            obj_config_usuariocolumna_.idusuario = UsuarioLOG.idusuario
            obj_config_usuariocolumna_.modulo = Me.Name
            'obj_config_usuariocolumna_.columnas = str_Columnas
            'obj_config_usuariocolumna_.columnasOrden = str_ColumnasOrden
            obj_config_usuariocolumna_.Nuevo()
        End If
    End Sub

    Public Overridable Sub bbi_imprimir_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_imprimir.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            ShowGridPreview(lbl_modulo.Text, gdc_general, False)
        End If
    End Sub

    Public Overridable Sub bbi_exportarPDF_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_exportarPDF.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            ExportGrid(lbl_modulo.Text, gdc_general, "PDF")
        End If
    End Sub

    Public Overridable Sub bbi_vistaprevia_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_vistaprevia.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            'i.Detail.
            ShowGridPreview(lbl_modulo.Text, gdc_general, True)
        End If
    End Sub

    Public Overridable Sub bbi_exportarExcel_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_exportarExcel.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            ExportGrid(lbl_modulo.Text, gdc_general, "XLS")
        End If
    End Sub

    Private Sub btn_Cerrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Cerrar.Click
        Me.Close()
    End Sub

    Private Sub bbi_Buscar_CheckedChanged(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_Buscar.CheckedChanged
        If bbi_Buscar.Checked Then
            gdv_general.ShowFindPanel()
        Else
            gdv_general.HideFindPanel()
        End If
    End Sub

    Public Overridable Sub IniciarLista()
    End Sub
  
    Private Sub bbi_actualizar_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_actualizar.ItemClick
        dtt_DataTable = New DataTable
        IniciarLista()
    End Sub

    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()
        Me.Icon = ico_AppIcono
     

        ' Add any initialization after the InitializeComponent() call.

    End Sub

    Private Sub txt_filtrarcol1_ButtonClick(ByVal sender As Object, ByVal e As DevExpress.XtraEditors.Controls.ButtonPressedEventArgs) Handles txt_filtrarcol1.ButtonClick
        gdv_general.ClearColumnsFilter()
        If CType(sender, DevExpress.XtraEditors.TextEdit).Text <> "" Then
            gdv_general.VisibleColumns(0).FilterInfo = New DevExpress.XtraGrid.Columns.ColumnFilterInfo("[" & gdv_general.VisibleColumns(0).ToString & "] Like '%" & CType(sender, DevExpress.XtraEditors.TextEdit).Text & "%'")
        End If
    End Sub

    Private Sub txt_filtrarcol1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txt_filtrarcol1.KeyPress
        If e.KeyChar = Chr(13) Then
            txt_filtrarcol1_ButtonClick(sender, Nothing)
        End If
    End Sub

    Private Sub txt_filtrarcol1_EditValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txt_filtrarcol1.EditValueChanged

    End Sub

    Private Sub lbl_modulo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles lbl_modulo.Click

    End Sub

    Private Sub lbl_modulo_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lbl_modulo.TextChanged
        Me.Text = lbl_modulo.Text
        lbl_modulodescripcion.Text = "Listado de " & lbl_modulo.Text & "."
    End Sub

    Private Sub Form_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        Cargarregistroestado_()
    End Sub

    Private Sub Cargarregistroestado_()
        Dim tmp_obj As Object = Nothing
        rep_cbo_estado.Items.Clear()
        Dim registroestado_ As New cls_registroestado_()
        registroestado_.CargarTodos()
        For Each obj As cls_registroestado_ In registroestado_.Items
            rep_cbo_estado.Items.Add(obj)
        Next

        If Not rep_cbo_estado.Items Is Nothing And Not registroestado_.Items Is Nothing Then
            If registroestado_.Items.Count > 0 And rep_cbo_estado.Items.Count > 0 Then
                cbo_estado.EditValue = registroestado_.Items(0)
            End If
        End If
    End Sub

    'Private Sub btnBuscar_ItemClick(sender As System.Object, e As DevExpress.XtraBars.ItemClickEventArgs)
    '    CargarLista()
    'End Sub

    Private Sub CargarLista()
        dtt_DataTable = New DataTable
        IniciarLista()
    End Sub

    Public Function ObtenerRegistroEstado() As Integer
        Dim idregistroestado = 1
        If (Not cbo_estado.EditValue Is Nothing) Then
            idregistroestado = CType(cbo_estado.EditValue, cls_registroestado_).idregistroestado
        End If
        Return idregistroestado
    End Function

    Private Sub cbo_estado_EditValueChanged(sender As System.Object, e As System.EventArgs) Handles cbo_estado.EditValueChanged
        CargarLista()
    End Sub
End Class